<template>
  <el-form class="BaseForm" ref="form" :model="prompt" label-width="88px" label-position="top">
    <div class="formContent">
      <div class="formTitle">模特图片</div>
      <el-form-item class="formItem">
        <ImagePicker TipsTxt="请上传需要替换模特的图片" ToPlatform="No-ComfyUI" @change="ChangeModelImg" :DefaultImageUrl="imageUrl" :Doodle="true" :MarkImageUrl="doodleMarkProview" @doodleImg="onDoodleImg"></ImagePicker>
      </el-form-item>
      <div class="formTitle">保留部分</div>
      <el-form-item class="formItem formCheckboxWrap">
        <el-checkbox class="formCheckbox" v-model="saveTops" label="上衣" border />
        <el-checkbox class="formCheckbox" v-model="saveCoat" label="外套" border />
        <el-checkbox class="formCheckbox" v-model="saveSkirt" label="裙装" border />
        <el-checkbox class="formCheckbox" v-model="savePants" label="裤装" border />
        <el-checkbox class="formCheckbox" v-model="saveBag" label="包类" border />
        <el-checkbox class="formCheckbox" v-model="saveShoes" label="鞋子" border />
        <el-checkbox class="formCheckbox" v-model="saveHat" label="帽子" border />
      </el-form-item>
      <div class="formTitle">背景描述</div>
      <el-form-item class="formItem">
        <!-- <el-input v-model="prompt.txt" type="textarea" :placeholder="promptTips()" rows="6"></el-input> -->
        <LilithChat v-model:text="prompt.txt" :placeholder="promptTips()" rows="6" :robot="true" />
      </el-form-item>
      <div class="formTitle">不期望生成</div>
      <el-form-item class="formItem">
        <!-- <el-input v-model="negativePrompt" type="textarea" placeholder="如有不希望包含的内容，请在此填写" rows="6"></el-input> -->
        <LilithChat v-model:text="negativePrompt" placeholder="如有不希望包含的内容，请在此填写" rows="6" :robot="true" />
      </el-form-item>
    </div>
    <div class="formBottomBar">
      <div class="content">
        <div class="tips">描述建议<br />场景 + 灯光 + 颜色 </div>
      </div>
      <el-button round class="FormBtn" @click="onSubmit" v-loading='isLoadingPrompt'><el-icon class="icon"><Brush /></el-icon><span class="txt">生成图片</span></el-button>
    </div>
    <el-dialog class="doodle-dialog" v-model="showDoodle" :destroy-on-close="false" :style="{minWidth: '432px'}">
      <Doodle :src="doodleSrc" :width="400" :height="400" @comfirm="onDoodleComfirm"/> 
    </el-dialog>
  </el-form>
</template>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
<script>
import WebRequest from '../../unit/request.js'
import PromptSession from '../element/PromptSession.vue'
import ImagePicker from '../element/ImagePicker.vue'
import Doodle from '../element/Doodle.vue'
import OS from '../../unit/OS.js'
import MergeMark from '../../unit/mergeMark.js'
import LilithChat from '../element/LilithChat.vue'
export default {
  name: 'ChangeModel',
  components: { PromptSession, ImagePicker, Doodle, LilithChat },
  props: {
    src: '',
    title: '',
    date: '',
    imageUrl: '',
  },
  data () {
    return {
      toolType:13,
      prompt: {
        txt: 'street',
        sessionData: []
      },
      maskImage: '',
      originalImage:'',
      negativePrompt: 'Low quality, cross eyed',
      defaultNegative: 'naked,nsfw,(worst quality:2),(low quality:2),(normal quality:2),lowres,watermark',
      isLoadingPrompt: false,
      saveTops:false,
      saveCoat:false,
      saveSkirt:false,
      savePants:false,
      saveBag:false,
      saveShoes:false,
      saveHat:false,
      showDoodle:false,
      doodleSrc:null,
      doodleMarkProview:null,
      doodleMarkImage:null,
    }
  },
  methods: {  
    promptTips () {
      var tips = [
        '一条热闹的大街，两边充满烟火气',
        '咖啡店门口，傍晚，天空有火烧云',
        '一个热闹的办公室，落地玻璃窗外是蓝天白云',
        '夜晚的酒吧街，两边是冷光的霓虹灯。'
      ]
      var random = Math.floor(Math.random() * tips.length)
      if (random >= tips.length) {
        random = 0
      }
      return tips[random]
    },
    ChangeModelImg (e) {
      console.log(e);
      if(e.fileName && e.fileName != null && e.fileName!=''){
        this.originalImage = e.fileName
      }else{
        this.originalImage = e.imageUrl
      }
      this.doodleSrc = null
      this.doodleMarkProview = null
      this.doodleMarkImage = null
      console.log(this.originalImage)
    },
    onSubmit(){
      var self = this;
      if(this.prompt.txt == ''){
        alert('请填写背景描述');
      }else if(this.originalImage == null || this.originalImage == ''){
        alert('请先选择模特图片');
      }else{
        //使用阿里云接口进行图像切割;
        var clothClassStr = '';
        if(this.saveTops){
          if(clothClassStr==''){
            clothClassStr= 'tops'
          }else{
            clothClassStr+=',tops'
          }
        }
        if(this.saveCoat){
          if(clothClassStr==''){
            clothClassStr= 'coat'
          }else{
            clothClassStr+=',coat'
          }
        }
        if(this.saveSkirt){
          if(clothClassStr==''){
            clothClassStr= 'skirt'
          }else{
            clothClassStr+=',skirt'
          }
        }
        if(this.savePants){
          if(clothClassStr==''){
            clothClassStr= 'pants'
          }else{
            clothClassStr+=',pants'
          }
        }
        if(this.saveBag){
          if(clothClassStr==''){
            clothClassStr= 'bag'
          }else{
            clothClassStr+=',bag'
          }
        }
        if(this.saveShoes){
          if(clothClassStr==''){
            clothClassStr= 'shoes'
          }else{
            clothClassStr+=',shoes'
          }
        }
        if(this.saveHat){
          if(clothClassStr==''){
            clothClassStr= 'hat'
          }else{
            clothClassStr+=',hat'
          }
        }
        WebRequest.SegmentCloth({
          clothClass:clothClassStr,// 'tops,coat,skirt,pants,bag,shoes,hat',
          imageURL: this.originalImage,
          returnForm: 'mask',
          callback: (scRes) => {
            console.log('SegmentCloth callback:',scRes.data.body.Data.Elements[0].ImageURL)
            // 合并遮罩图
            let ClassUrl = scRes.data.body.Data.Elements[1].ClassUrl
            let markList = []
            for (const k in ClassUrl) {
              markList.push(ClassUrl[k])
            }
            MergeMark.getImageInfo(scRes.data.body.Data.Elements[0].ImageURL).then(img => {
              MergeMark.mergeMark({
                width: img.width,
                height: img.height,
                images: markList,
                type: 'base64',
                canNotImages: true, // 允许不合成遮罩
                success: (resMarkImage) => {
                  console.log('遮罩合并成功', resMarkImage)
                  if (this.doodleMarkImage) {
                    resMarkImage = this.doodleMarkImage
                  }
                  // 上次base64图片到oss换取oss地址
                  WebRequest.UploadImageDataToOss({
                    picBase64: resMarkImage,
                    callback: (imgRes) => {
                      let markImage = imgRes.data.data
                      // 换取线上oss遮罩图
                      WebRequest.UploadWebImageToOss({
                        url: markImage,
                        callback: (res) => {
                          console.log('UploadWebImageToOss callback:',res)
                          var negative = this.defaultNegative
                          if(res.data.errCode == 10000){
                            if(this.negativePrompt != null && this.negativePrompt != ''){
                              negative =this.negativePrompt + ',' + negative
                            }
                            WebRequest.ModelSwap({
                              maskImage: res.data.data,
                              originalImage: this.originalImage.replace('https://picture.2beauti.com','https://beauti-img.oss-cn-shenzhen.aliyuncs.com'),
                              prompt: this.prompt.txt,
                              negativePrompt: negative,
                              callback: (e) => {
                                console.log('model swap callback:',e)
                                //this.$emit('StartGenerate',e);
                                this.$emit('StartGenerate')
                                if(e.data.errCode == 10000){
                                  var genSuccess = 0
                                  var called = true
                                  var call = setInterval(() => {
                                    if(called){
                                        called = false
                                        WebRequest.GetComfyuiFileName({
                                          promptId:e.data.data,
                                          callback: (res_1) =>{
                                            //console.log('GetComfyuiFileName',res_1)
                                            if(res_1.data.errCode == 10000){
                                              WebRequest.GetComfyuiFileUrl({
                                                fileName:res_1.data.data,
                                                callback: (res_2) =>{
                                                  //console.log('GetComfyuiFileUrl',res_2)
                                                  if(res_2.data.errCode == 10000){
                                                    genSuccess=1
                                                    this.$emit('ResultCalled',res_2.data.data)
                                                  }
                                                  called = true
                                                  clearInterval(call)
                                                },
                                                error:(res_2)=>{
                                                  called = true
                                                  clearInterval(call)
                                                }
                                              })
                                            }else{
                                              called = true
                                              //lclearInterval(call)
                                            }
                                          }
                                        })
                                      }
                                  },2000)
                                }else{
                                  console.log('model swap error',e)
                                }
                              },
                              error: (e) => {
                                console.log('model swap call error:',e)
                              }
                            })

                          }else{
                            console.log('uploadWebImageToOss fail', scRes)
                          }
                        }
                      })
                    },
                    error: (imgErr) => {
                      console.log(imgErr)
                    }
                  })
                },
                fail: err => {
                  console.log(err);
                }
              })
            })
          },
          error: (res) => {
            console.log('segment cloth call error:', res)
          }
        })
      }
    },
    // 触发涂抹
    onDoodleImg(img) {
      if (img) {
        this.doodleSrc = img
        this.showDoodle = true
      }
    },
    onDoodleComfirm(imgs) {
      console.log('确认涂抹完成')
      this.showDoodle = false
      this.doodleMarkProview = imgs.original
      this.doodleMarkImage = imgs.mark
    },
  }
}
</script>
